package ${package}.${rootArtifactId}.common.util;

import java.util.concurrent.TimeUnit;

/**
 * 分布式工具
 *
 * @author weidong.lin
 * @date 2021/7/8 11:06
 */
public class DistributedLocksUtil {

    /**
     * redis lock
     *
     * @param key           key
     * @param maxLockSecond 最大锁秒数
     * @return true or false
     */
    public static boolean lock(String key, long maxLockSecond) {
        long t = System.currentTimeMillis();
        long expTime = t + maxLockSecond * 1000;
        boolean signed = RedisUtil.setIfAbsent(key, String.valueOf(expTime));
        if (!signed) {
            Long oldTime = NumberUtil.parseLong(RedisUtil.get(key));
            if (oldTime == null || oldTime < t) {
                Long replaced = NumberUtil.parseLong(RedisUtil.getAndSet(key, String.valueOf(expTime)));
                boolean valid = (replaced == null || (oldTime != null && replaced.compareTo(oldTime) == 0));
                if (valid) {
                    signed = true;
                }
            }
        }
        if (signed) {
            RedisUtil.expire(key, maxLockSecond, TimeUnit.SECONDS);
        }
        return signed;
    }

}
